/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.jr2tecnologia.model.persistence;

import br.com.jr2tecnologia.LoggerFactory;
import br.com.jr2tecnologia.model.entity.Company;
import br.com.jr2tecnologia.model.repository.CompanyRepository;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;


/**
 *
 * @author ronildo
 */
public class CompanyDAO extends GenericDAO<Company, CompanyRepository> implements CompanyRepository {

    private static final Logger logger = LoggerFactory.getLogger();

    public Company findById(Long id) {
        return (Company)em.createNamedQuery("Company.findByPkCompany").
                setParameter("pkCompany", id).getSingleResult();
    }

    public Company findByName(String name) {
        try{
            return (Company)em.createNamedQuery("Company.findByName").
                setParameter("name", name).getSingleResult();
        }catch(NoResultException e){
            logger.log(Level.WARNING, "Cannot find data");
            return null;
        }catch(NonUniqueResultException e){
            logger.log(Level.WARNING, "Have more than one result");
            throw new DAOException(e);
        }catch(IllegalStateException e){
            logger.log(Level.SEVERE, msg, e);
            throw new DAOException(e);
        }
    }

    public List<Company> list(Company company) {
        try{
            String hql = "SELECT company FROM Company company where company.pkCompany = company.pkCompany";
            if(company.getName() != null && !company.getName().equals(""))
                hql+=" and company.name like :company_name";
            hql+=" order by company.name";

            Query query = em.createQuery(hql);
            if(company.getName() != null && !company.getName().equals(""))
                query.setParameter("company_name", company.getName()+"%");

            return query.getResultList();
        }catch(RuntimeException e){
            logger.log(Level.SEVERE, "Error to list company",e);
            throw new DAOException(e);
        }
    }

    public List<Company> listAll() {
        try{
            return em.createNamedQuery("Company.findAll").getResultList();
        }catch(IllegalStateException e){
            logger.log(Level.SEVERE, msg, e);
            throw new DAOException(e);
        }
    }

}
